﻿using PMS.Data.Entities.ScheduleTasks;
using PMS.Services.EntityServices.SchduleTasks;
using PMS.Services.Utils;
using PMS.Web.Framework.Models;
using PMS.Web.Models;
using PMS.Web.Models.ScheduleTasks;
using System.Linq;

namespace PMS.Web.Factories.ScheduleTasks
{
    public class ScheduleTaskFactory : IScheduleTaskFactory
    {
        #region Fields
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly IScheduleTaskService _scheduleTaskService;
        #endregion

        #region Ctor
        public ScheduleTaskFactory(IDateTimeHelper dateTimeHelper,
            IScheduleTaskService scheduleTaskService)
        {
            _dateTimeHelper = dateTimeHelper;
            _scheduleTaskService = scheduleTaskService;
        }
        #endregion

        #region Utils
        private ScheduleTaskModel ConvertToModel(SystemScheduleTask entity)
        {
            var model = entity.ToModel<ScheduleTaskModel>();
            if (entity.LastStartTimeUtc.HasValue)
                model.LastStartTime = _dateTimeHelper.ConvertToStoreTime(entity.LastStartTimeUtc.Value);
            if (entity.LastStopTimeUtc.HasValue)
                model.LastStopTime = _dateTimeHelper.ConvertToStoreTime(entity.LastStopTimeUtc.Value);
            if (entity.LastSuccessTimeUtc.HasValue)
                model.LastSuccessTime = _dateTimeHelper.ConvertToStoreTime(entity.LastSuccessTimeUtc.Value);
            return model;
        }
        #endregion

        #region Methods
        public virtual ScheduleTaskListModel PrepareScheduleTaskListModel(int page = 1, int pageSize = int.MaxValue)
        {
            var pagedTasks = _scheduleTaskService.GetPagedTasks(page - 1, pageSize, true);
            var models = new ScheduleTaskListModel().PrepareToGrid(pagedTasks, () =>
            {
                return pagedTasks.Select(task => ConvertToModel(task));
            });
            return models;
        }

        /// <summary>
        /// Prepare ScheduleTaskModel by taskid
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public virtual ScheduleTaskModel PrepareScheduleTaskModel(int taskid)
        {
            var task = _scheduleTaskService.GetTaskById(taskid);
            return PrepareScheduleTaskModel(task);
        }

        /// <summary>
        /// Prepare ScheduleTaskModel by task entity
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public virtual ScheduleTaskModel PrepareScheduleTaskModel(SystemScheduleTask task)
        {
            return task == null ? null : ConvertToModel(task);
        }
        #endregion
    }
}
